<template>
  <div class="basic-info">
    <el-form :model="formData" :label-width="labelWidth" class="archive-form">
      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item :label="t('healthRecords.basicInfo.fields.userName')">
            <el-input
              v-model="formData.userName"
              :placeholder="t('healthRecords.basicInfo.placeholders.enter')"
              :disabled="!isEditing"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item :label="t('healthRecords.basicInfo.fields.gender')">
            <el-select
              v-model="formData.gender"
              :placeholder="t('healthRecords.basicInfo.placeholders.select')"
              class="w-full"
              :disabled="!isEditing"
            >
              <el-option
                :label="t('healthRecords.basicInfo.genderOptions.male')"
                value="1"
              />
              <el-option
                :label="t('healthRecords.basicInfo.genderOptions.female')"
                value="2"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item :label="t('healthRecords.basicInfo.fields.birthDate')">
            <el-date-picker
              v-model="formData.birthDate"
              type="date"
              :placeholder="t('healthRecords.basicInfo.placeholders.select')"
              class="w-full"
              :disabled="!isEditing"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item :label="t('healthRecords.basicInfo.fields.ethnicity')">
            <el-select
              v-model="formData.ethnicity"
              :placeholder="t('healthRecords.basicInfo.placeholders.select')"
              class="w-full"
              :disabled="!isEditing"
            >
              <el-option
                v-for="item in ETHNICITY_OPTIONS"
                :key="item.value"
                :label="item.text"
                :value="item.text"
              />
              <!-- 其他民族选项可以从字典数据获取 -->
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item :label="t('healthRecords.basicInfo.fields.phone')">
            <el-input
              v-model="formData.phone"
              :placeholder="t('healthRecords.basicInfo.placeholders.enter')"
              :disabled="!isEditing"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item :label="t('healthRecords.basicInfo.fields.idCard')">
            <el-input
              v-model="formData.idCard"
              :placeholder="t('healthRecords.basicInfo.placeholders.enter')"
              :disabled="!isEditing"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item
            :label="t('healthRecords.basicInfo.fields.emergencyContactName')"
          >
            <el-input
              v-model="formData.emergencyContactName"
              :placeholder="t('healthRecords.basicInfo.placeholders.enter')"
              :disabled="!isEditing"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item
            :label="t('healthRecords.basicInfo.fields.emergencyContactPhone')"
          >
            <el-input
              v-model="formData.emergencyContactPhone"
              :placeholder="t('healthRecords.basicInfo.placeholders.enter')"
              :disabled="!isEditing"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item
            :label="t('healthRecords.basicInfo.fields.emergencyContactAddress')"
          >
            <el-input
              v-model="formData.emergencyContactAddress"
              :placeholder="t('healthRecords.basicInfo.placeholders.enter')"
              :disabled="!isEditing"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item :label="t('healthRecords.basicInfo.fields.education')">
            <el-select
              v-model="formData.education"
              :placeholder="t('healthRecords.basicInfo.placeholders.select')"
              class="w-full"
              :disabled="!isEditing"
            >
              <el-option
                v-for="item in EDUCATION_OPTIONS"
                :key="item.value"
                :label="item.text"
                :value="item.text"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item :label="t('healthRecords.basicInfo.fields.occupation')">
            <el-input
              v-model="formData.occupation"
              :placeholder="t('healthRecords.basicInfo.placeholders.enter')"
              :disabled="!isEditing"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item
            :label="t('healthRecords.basicInfo.fields.maritalStatus')"
          >
            <el-select
              v-model="formData.maritalStatus"
              placeholder="请选择婚姻状况"
              :disabled="!isEditing"
            >
              <el-option
                v-for="option in MARITAL_STATUS_OPTIONS"
                :key="option.value"
                :label="option.text"
                :value="option.text"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item
            :label="t('healthRecords.basicInfo.fields.medicalInsurance')"
          >
            <el-input
              v-model="formData.medicalInsurance"
              :placeholder="t('healthRecords.basicInfo.placeholders.enter')"
              :disabled="!isEditing"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item
            :label="t('healthRecords.basicInfo.fields.livingHistory')"
          >
            <el-input
              v-model="formData.livingHistory"
              :placeholder="t('healthRecords.basicInfo.placeholders.enter')"
              :disabled="!isEditing"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item
            :label="t('healthRecords.basicInfo.fields.workHistory')"
          >
            <el-input
              v-model="formData.workHistory"
              :placeholder="t('healthRecords.basicInfo.placeholders.enter')"
              :disabled="!isEditing"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <div class="flex justify-end mt-4 gap-4">
        <el-button @click="handleEdit">{{
          t("healthRecords.basicInfo.buttons.edit")
        }}</el-button>
        <el-button type="primary" @click="handleSave">{{
          t("healthRecords.basicInfo.buttons.save")
        }}</el-button>
      </div>
    </el-form>
  </div>
</template>

<script lang="ts" setup>
import type { HealthArchiveBaseInfo } from "@/api/health";
import { healthApi } from "@/api/health";
import {
  EDUCATION_OPTIONS,
  ETHNICITY_OPTIONS,
  MARITAL_STATUS_OPTIONS
} from "@/constants/common-const";
import { ElMessage } from "element-plus";
import { computed, onMounted, reactive, ref, watch } from "vue";
import { useI18n } from "vue-i18n";
const props = defineProps<{
  archiveInfo?: HealthArchiveBaseInfo;
  requestSource?: number;
}>();

const emit = defineEmits<{
  (e: "update-success"): void;
}>();

// 国际化
const { t, locale } = useI18n();

// 是否处于编辑状态
const isEditing = ref(false);

// 根据语言状态动态调整label宽度
const labelWidth = computed(() => {
  // 英文状态下为130px，中文状态下为110px
  return locale.value === "en" ? "130px" : "110px";
});

interface FormData extends HealthArchiveBaseInfo {
  userName?: string;
}

// 表单数据
const formData = reactive<FormData>({
  userId: 0,
  userName: "",
  gender: "",
  birthDate: "",
  ethnicity: "",
  phone: "",
  idCard: "",
  emergencyContactName: "",
  emergencyContactPhone: "",
  emergencyContactAddress: "",
  education: "",
  occupation: "",
  maritalStatus: "",
  medicalInsurance: "",
  livingHistory: "",
  workHistory: ""
});

// 监听props变化，更新表单数据
watch(
  () => props.archiveInfo,
  (newVal, oldVal) => {
    if (newVal) {
      console.log("档案信息数据更新:", {
        新数据: newVal,
        旧数据: oldVal,
        数据来源: props.requestSource
      });

      // 更新表单数据
      Object.assign(formData, newVal);

      console.log("表单数据已更新:", formData);
    } else {
      console.log("未接收到档案信息数据");
    }
  },
  { immediate: true }
);

// 编辑按钮点击事件
const handleEdit = () => {
  console.log("开始编辑基本信息", {
    当前表单数据: formData,
    编辑状态: isEditing.value
  });

  isEditing.value = true;
  ElMessage.success(t("healthRecords.basicInfo.messages.editMode"));

  console.log("编辑模式已开启");
};

// 保存按钮点击事件
const handleSave = async () => {
  try {
    // 构建基本信息数据，排除不属于HealthArchiveBaseInfo的字段
    const basicInfoData: HealthArchiveBaseInfo = {
      userId: formData.userId || props.archiveInfo?.userId || 0,
      gender: formData.gender,
      birthDate: formData.birthDate,
      ethnicity: formData.ethnicity,
      phone: formData.phone,
      idCard: formData.idCard,
      emergencyContactName: formData.emergencyContactName,
      emergencyContactPhone: formData.emergencyContactPhone,
      emergencyContactAddress: formData.emergencyContactAddress,
      education: formData.education,
      occupation: formData.occupation,
      maritalStatus: formData.maritalStatus,
      medicalInsurance: formData.medicalInsurance,
      livingHistory: formData.livingHistory,
      workHistory: formData.workHistory,
      archiveId: formData.archiveId,
      requestSource: props.requestSource
    };

    console.log("准备提交的基本信息数据:", basicInfoData);

    // 调用保存接口
    const response = await healthApi.getHealthArchiveUpdateBasic(basicInfoData);

    console.log("保存接口响应:", response);
    emit("update-success");

    isEditing.value = false;
  } catch (error) {
    console.error("保存基本信息时发生异常:", {
      错误信息: error.message,
      错误堆栈: error.stack,
      当前数据: formData
    });
    ElMessage.error(t("healthRecords.basicInfo.messages.saveFailedRetry"));
  }
};

onMounted(() => {
  console.log("BasicInfo组件已挂载", {
    初始表单数据: formData,
    传入的档案信息: props.archiveInfo,
    请求来源: props.requestSource,
    当前语言: locale.value
  });

  // 可以在这里加载一些字典数据，比如民族列表等
  console.log("BasicInfo组件初始化完成");
});
</script>

<style lang="scss" scoped>
.basic-info {
  padding: 20px 0;

  .archive-form {
    .el-form-item {
      margin-bottom: 18px;
    }

    :deep(.el-input),
    :deep(.el-select),
    :deep(.el-date-picker) {
      width: 100%;
    }
  }
}
</style>
